package main

import (
	"flag"
	"fmt"
	"net/http"
)

var store *UrlStore

func Redirect(w http.ResponseWriter, req *http.Request) {
	key := req.URL.Path[1:]
	url := store.Get(key)
	if url == "" {
		http.NotFound(w, req)
	}
	http.Redirect(w, req, url, http.StatusFound)
}

const AddForm = `
<html>
<form method="POST" action="/add">
URL: <input type="text" name="url">
<input type="submit" value="Add">
</form>
</html>
`

func Add(w http.ResponseWriter, req *http.Request) {
	url := req.FormValue("url")
	if url == "" {
		fmt.Fprintf(w, AddForm)
		return
	}
	key := store.Put(url)
	fmt.Fprintf(w, "http://%s/%s", *hostname, key)
}

var (
	storeFileName = flag.String("file", "store.gob", "store file name")
	listenAddr    = flag.String("http", ":8080", "http listen addr")
	hostname      = flag.String("host", "localhost:8080", "http host name")
)

func main() {
	flag.Parse()
	store = NewUrlStore(*storeFileName)
	fmt.Println("web server go v5 start ....")
	http.HandleFunc("/", Redirect)
	http.HandleFunc("/add", Add)
	http.ListenAndServe(*listenAddr, nil)
}
